<?php

namespace app\api\controller;

use app\api\common\Program;
use app\common\controller\Api;
use app\api\common\WxPay;
use app\api\common\AppPay;
use app\common\model\UserCircle;
use app\common\model\UserCircle as UserCircleModel;
use app\common\model\UserCirclePrice as UserCirclePriceModel;
use app\common\model\Report as ReportModel;
use app\common\model\Config as ConfigModel;
use think\Validate;
use think\Db;

/**
 * 帖子接口
 */
class Posts extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['getCircleShareInfo','getCateCircle','getCircleInfo'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    /**
     * 测试方法
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */

    /*
     * 车辆类型
     * @path api/posts/getVehicleList
     * */
    public function getVehicleList()
    {
        $where = "id > 0";
        $field = "id,name";
        $order = "weigh DESC,add_time DESC";
        $list = Db::name("vehicle")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /**
     * 举报原因
     * @path api/posts/getReportReason
     */
    public function getReportReason()
    {
        $where = "is_del = '0'";
        $field = "id,name";
        $order = "weigh DESC,add_time DESC";
        $list = Db::name("report_reason")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /**
     * 置顶时长
     * @path api/posts/getTopPrice
     * @param int type 1:首页置顶,2:分类置顶
     */
    public function getTopPrice()
    {
        $type = (string)$this->request->param("type");
        if(!$type){
            $this->error("置顶类型不能为空");
        }
        $where = "type = {$type}";
        $field = "id,day,price";
        $order = "day ASC";
        $list = Db::name("topprice")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /*
     * 帖子中心
     * @path api/posts/getCateCircle
     * */
    public function getCateCircle()
    {
        $page = $this->request->param("page",1);
        $cate_id = $this->request->param("cate_id",0);
        $sort_type = $this->request->param("sort_type",0);
        $province_id = $this->request->param("province_id",0);
        $city_id = $this->request->param("city_id",0);
        $area_id = $this->request->param("area_id",0);
        $title = $this->request->param("title","");
        $user_id = $this->auth->user_id;
        $list = UserCircleModel::get_cate_circle($page,$cate_id,$sort_type,$title,$province_id,$city_id,$area_id,$user_id);
        $this->success("请求成功",$list);
    }

    /**
     * 帖子详情
     * @path api/posts/getCircleInfo
     */
    public function getCircleInfo()
    {
        $user_id = $this->request->param('user_id',0);
        $circle_id = $this->request->param("circle_id");
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        $infoMsg = UserCircleModel::get($circle_id);
        if(!$infoMsg){
            $this->error("帖子ID错误");
        }
        $info = UserCircleModel::get_circle_info($circle_id,$user_id);
        $this->success('请求成功', $info);
    }

    /**
     * 帖子信息
     * @path api/posts/getCircleMsg
     */
    public function getCircleMsg()
    {
        $user_id = $this->auth->user_id;
        $circle_id = $this->request->param("circle_id");
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        $infoMsg = UserCircleModel::get($circle_id);
        if(!$infoMsg){
            $this->error("帖子ID错误");
        }
        $info = UserCircleModel::get_circle_msg($circle_id,$user_id);
        $this->success('请求成功', $info);
    }

    /**
     * 分享帖子信息
     * @path api/posts/getCircleShareInfo
     */
    public function getCircleShareInfo()
    {
        $params = $this->request->param();
        $circle_id = $params["params"]["circle_id"];
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        $infoMsg = UserCircleModel::get($circle_id);
        if(!$infoMsg){
            $this->error("帖子ID错误");
        }
        $info = UserCircleModel::get_circle_share_info($circle_id);
        $this->success('请求成功', $info);
    }

    /**
     * 收藏帖子/取消收藏
     * @path api/posts/circleCollect
     * @param int $circle_id 帖子id
     */
    public function circleCollect()
    {
        $user_id = $this->auth->user_id;
        $circle_id = $this->request->param("circle_id",0);
        if(!$circle_id){
            $this->error("贴子ID不能为空");
        }
        $isset = Db::name("collect")->where("circle_id = $circle_id AND user_id = $user_id")->find();
        if ($isset){
            $res = Db::name("collect")->where("circle_id = $circle_id AND user_id = $user_id")->delete();
            if ($res){
                UserCircleModel::where("id",$circle_id)->setDec('collect_count',1);
                $this->success("取消成功");
            }else{
                $this->error("取消失败");
            }
        }else{
            $other_id = UserCircleModel::where("id",$circle_id)->value("user_id");
            $collect_data = [];
            $collect_data["user_id"] = $user_id;
            $collect_data["other_id"] = $other_id;
            $collect_data["circle_id"] = $circle_id;
            $collect_data["add_time"] = time();
            $res = Db::name("collect")->insert($collect_data);
            if ($res){
                UserCircleModel::where("id",$circle_id)->setInc('collect_count',1);
                $this->success('收藏成功');
            }else{
                $this->error('收藏失败');
            }
        }
    }

    /**
     * 举报帖子
     * @path api/posts/reportCircle
     */
    public function reportCircle()
    {
        $circle_id = $this->request->param("circle_id");
        $reason_id = $this->request->param("reason_id");
        $content = $this->request->param("content");
        $user_id = $this->auth->user_id;
        if(!$circle_id){
            $this->error("帖子ID不能为空");
        }
        if(!$reason_id){
            $this->error("举报原因不能为空");
        }
        $res = ReportModel::addReport($user_id,$circle_id,$reason_id,$content);
        if($res){
            $this->success("举报成功");
        }else{
            $this->error("举报失败");
        }
    }

    /**
     * 发布帖子
     * @path api/posts/releaseCircle
     */
    public function releaseCircle()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        if($params['index_top'] == "不置顶"){
            $params['index_top'] = 0;
        }
        if($params['cate_top'] == "不置顶"){
            $params['cate_top'] = 0;
        }
        $circle_price = ConfigModel::getConfigValue("circle_price");
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!$user['tel']){
            $this->error("请先绑定手机号");
        }
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        if($user["authen"] == 3){
            $circle_price = 0;
        }
        $data = [
            'cate_id'=>$params["cate_id"], //二手车分类ID
            'vehicle_id'=>$params["vehicle_id"], //车辆类型ID
            'province_id'=>$params["province_id"], //省ID
            'city_id'=>$params["city_id"], //市ID
            'area_id'=>$params["area_id"], //区ID
            'title'=>$params["title"], //标题
            'content'=>$params["content"], //内容
            'image'=>$params["image"], //封面图
            'content_images'=>$params["content_images"], //内容图
            'price'=>$params["price"], //销售价
            'base_price'=>$params["base_price"], //可接受底价
        ];

        $role = [
            'cate_id' => 'require',
            'vehicle_id' => 'require',
            'province_id' => 'require',
            'city_id' => 'require',
            'area_id' => 'require',
            'title' => 'require',
            'content'=>'require',
            'image'=>'require',
            'content_images'=>'require',
            'price'=>'require',
            'base_price'=>'require',
        ];

        $msg = [
            'cate_id.require'=>'二手车分类不能为空',
            'vehicle_id.require'=>'车量类型不能为空',
            'province_id.require'=>'省不能为空',
            'city_id.require'=>'市不能为空',
            'area_id.require'=>'区不能为空',
            'title.require'=>'标题不能为空',
            'content.require'=>'内容不能为空',
            'image.require'=>'封面图不能为空',
            'content_images.require'=>'内容图不能为空',
            'price.require'=>'销售价不能为空',
            'base_price.require'=>'可接受底价不能为空',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        //小程序敏感词过滤
        if($user->open_id){
            $res = Program::TextRecognition($params['title'],$user->open_id);
            if($res['code'] == 200 && $res['label'] != 100){
                $this->error($res['data']);
            }elseif ($res['code'] == 201) {
                $this->error($res['data']);
            }
            $res = Program::TextRecognition($params['content'],$user->open_id);
            if($res['code'] == 200 && $res['label'] != 100){
                $this->error($res['data']);
            }elseif ($res['code'] == 201) {
                $this->error($res['data']);
            }
        }
        //敏感词判断
        $sensitive = UserCircleModel::sensitivewords();
        $filteredTitle = replaceSensitiveWords($params['title'], $sensitive);
        $data["title"] = $filteredTitle;
        $post_content = replaceSensitiveWords($params['content'],$sensitive);
        //关键词判断
        $keywords = UserCircleModel::circleKeywords();
        $titleContainsSensitiveWords = containsSensitiveWords($params['title'], $keywords);
        $contentContainsSensitiveWords = containsSensitiveWords($params['content'], $keywords);
        if ($titleContainsSensitiveWords || $contentContainsSensitiveWords) {
            //echo "标题或内容中包含敏感关键词";
            $is_see = 1;
        } else {
            //echo "标题和内容中都不包含敏感关键词";
            $is_see = 0;
        }
        $data["content"] = $post_content;
        $data["user_id"] = $user_id;
        $data["is_see"] = $is_see;
        if(isset($params["image"])){
            $data["image"] = parse_url($params["image"])["path"];
        }
        if(isset($params["content_images"]) && !empty($params["content_images"])){
            $content_images = explode(",",$params["content_images"]);
            foreach ($content_images as $key=>&$value){
                if($user->open_id){
                    $res = Program::VideoRecognition(parse_url($value)["path"],2,$user->open_id);
                    if($res['code'] == 200 && $res['label'] != 100){
                        $this->error($res['data']);
                    }elseif ($res['code'] == 201) {
                        $this->error($res['data']);
                    }
                }
                $value = parse_url($value)["path"];
            }
            $content_images_str = implode(",",$content_images);
        }else{
            $content_images_str = "";
        }
        $data["content_images"] = $content_images_str;
        $data["index_top"] = $params['index_top'];
        $data["cate_top"] = $params['cate_top'];
        if(containsPhoneNumber($post_content)){
            $this->error("发帖内容不能包含手机号");
        }
        if(empty($params['version']) || empty($params['duan'])){
            $this->error("参数异常");
        }
        $info = Db::name("version")->where(["newversion"=>$params["version"],"duan"=>$params["duan"]])->order("id","desc")->find();
        if(!$info){
            $this->error("当前版本信息有误");
        }
        if($info['status'] != '3'){
            $data['user_circle_price_id'] = 0;
            $res = UserCircleModel::create($data);
            if($res){
                $circle_id = $res->id;
                $circle_info = UserCircleModel::get($circle_id);
                $circle_log = [];
                $circle_log['circle_id'] = $circle_id;
                $circle_log['content'] = json_encode($circle_info);
                $circle_log['authen'] = 1;
                $circle_log['addtime'] = time();
                Db::name("user_circle_log")->insert($circle_log);
                $this->success("发布成功");
            }else{
                $this->error("发布失败");
            }
        }
        if(($params['index_top'] == 0 && $params['cate_top'] == 0 && $user["authen"] == 3 && $circle_price == 0) || ($params['index_top'] == 0 && $params['cate_top'] == 0 && $circle_price == 0)){
            $data['user_circle_price_id'] = 0;
            $res = UserCircleModel::create($data);
            if($res){
                $circle_id = $res->id;
                $circle_info = UserCircleModel::get($circle_id);
                $circle_log = [];
                $circle_log['circle_id'] = $circle_id;
                $circle_log['content'] = json_encode($circle_info);
                $circle_log['authen'] = 1;
                $circle_log['addtime'] = time();
                Db::name("user_circle_log")->insert($circle_log);
                $this->success("发布成功");
            }else{
                $this->error("发布失败");
            }
        }else{
            if($params['index_top'] != 0){
                $index_top_info = Db::name("topprice")->where(["type"=>1,"day"=>$params['index_top']])->find();
                if(!$index_top_info){
                    $this->error("首页置顶天数错误");
                }
                if($params["index_top_price"] != $index_top_info["price"]){
                    $this->error("首页置顶金额错误");
                }
            }
            if($params['cate_top'] != 0){
                $cate_top_info = Db::name("topprice")->where(["type"=>2,"day"=>$params["cate_top"]])->find();
                if(!$cate_top_info){
                    $this->error("分类置顶天数错误");
                }
                if($params["cate_top_price"] != $cate_top_info["price"]){
                    $this->error("分类置顶金额错误");
                }
            }
            if($params['is_top'] != 0 || $params['cate_top'] != 0){
                $pay_price = bcadd($circle_price,bcadd($params['index_top_price'],$params['cate_top_price'],2),2);
            }else{
                $pay_price = $circle_price;
            }
            if($params['pay_price'] != $pay_price){
                $this->error("支付金额错误");
            }
            $data['index_top_price'] = $params['index_top_price'];
            $data['cate_top_price'] = $params['cate_top_price'];
            $res = UserCircleModel::create($data);
            //写入发帖,修改帖记录
            $circle_id = $res->id;
            $circle_info = UserCircleModel::get($circle_id);
            $circle_log = [];
            $circle_log['circle_id'] = $circle_id;
            $circle_log['content'] = json_encode($circle_info);
            $circle_log['authen'] = 1;
            $circle_log['addtime'] = time();
            Db::name("user_circle_log")->insert($circle_log);
            $order_no = order_no("F");
            $circle_price_data = [];
            $circle_price_data['user_id'] = $user_id;
            $circle_price_data['circle_id'] = $res->id;
            $circle_price_data['index_top'] = $params['index_top'];
            $circle_price_data['cate_top'] = $params['cate_top'];
            $circle_price_data['index_top_price'] = $params['index_top_price'];
            $circle_price_data['cate_top_price'] = $params['cate_top_price'];
            $circle_price_data['circle_price'] = $circle_price;
            $circle_price_data['price'] = $params['pay_price'];
            $circle_price_data['order_no'] = $order_no;
            $circle_price_data['ispay'] = 0;
            $circle_price_data['duan'] = $params['duan'];
            UserCirclePriceModel::create($circle_price_data);
            if($params['duan'] == 1){
                $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','发帖置顶');
                return json_encode($pay_message);
            }else{
                $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','发帖置顶');
                return json_encode($pay_message);
            }
        }
    }

    /*
     * 个人主页
     * @path api/posts/getHomepage
     * */
    public function getHomepage()
    {
        $page = $this->request->param("page",1);
        $is_sale = $this->request->param("issale",0);
        $other_id = $this->request->param("other_id");
        $type = $this->request->param("type",0);
        if(isset($other_id) && !empty($other_id)){
            $user_id = $other_id;
        }else{
            $user_id = $this->auth->user_id;
        }
        $current_user_id = $this->auth->user_id;
        $list = UserCircleModel::get_home_page($page,$is_sale,$user_id,$type,$current_user_id);
        $this->success("请求成功",$list);
    }

    /*
     * 删除帖子
     * @path api/posts/delCircle
     * */
    public function delCircle()
    {
        $user_id = $this->auth->user_id;
        $circle_id = $this->request->param("circle_id");
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        $info = UserCircleModel::get($circle_id);
        if($user_id != $info->user_id){
            $this->error("无删除权限");
        }
        Db::name("collect")->where("circle_id",$circle_id)->delete();
        UserCircleModel::where("id",$circle_id)->delete();
        $this->success('删除成功');
    }

    /*
     * 隐藏
     * @path api/posts/isShowCircle
     * */
    public function isShowCircle()
    {
        $user_id = $this->auth->user_id;
        $circle_id = $this->request->param("circle_id");
        $is_show = $this->request->param("isshow");
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        if(!$is_show){
            $this->error("状态不能为空");
        }
        $where = "user_id = {$user_id}";
        $where.= " AND id = {$circle_id}";
        $info = UserCircleModel::where($where)->find();
        $info->isshow = $is_show;
        $info->save();
        $this->success('操作成功');
    }

    /**
     * 修改帖子
     * @path api/posts/modifyCircle
     */
    public function modifyCircle()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        $circle_id = $this->request->param("circle_id");
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        $circle_info = UserCircleModel::get($circle_id);
        if(!$circle_info){
            $this->error("帖子信息错误");
        }
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        if($user["authen"] == 3){
            $edit_price = 0;
            $circle_price = 0;
        }else{
            $edit_price = ConfigModel::getConfigValue("edit_price");
            $circle_price = ConfigModel::getConfigValue("circle_price");
        }
        $data = [
            'cate_id'=>$params["cate_id"], //二手车分类ID
            'vehicle_id'=>$params["vehicle_id"], //车辆类型ID
            'province_id'=>$params["province_id"], //省ID
            'city_id'=>$params["city_id"], //市ID
            'area_id'=>$params["area_id"], //区ID
            'title'=>$params["title"], //标题
            'content'=>$params["content"], //内容
            'image'=>$params["image"], //封面图
            'content_images'=>$params["content_images"], //内容图
            'price'=>$params["price"], //销售价
            'base_price'=>$params["base_price"], //可接受底价
        ];

        $role = [
            'cate_id' => 'require',
            'vehicle_id' => 'require',
            'province_id' => 'require',
            'city_id' => 'require',
            'area_id' => 'require',
            'title' => 'require',
            'content'=>'require',
            'image'=>'require',
            'content_images'=>'require',
            'price'=>'require',
            'base_price'=>'require',
        ];

        $msg = [
            'cate_id.require'=>'二手车分类不能为空',
            'vehicle_id.require'=>'车量类型不能为空',
            'province_id.require'=>'省不能为空',
            'city_id.require'=>'市不能为空',
            'area_id.require'=>'区不能为空',
            'title.require'=>'标题不能为空',
            'content.require'=>'内容不能为空',
            'image.require'=>'封面图不能为空',
            'content_images.require'=>'内容图不能为空',
            'price.require'=>'销售价不能为空',
            'base_price.require'=>'可接受底价不能为空',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        //小程序敏感词过滤
        if($user->open_id){
            $res = Program::TextRecognition($params['title'],$user->open_id);
            if($res['code'] == 200 && $res['label'] != 100){
                $this->error($res['data']);
            }elseif ($res['code'] == 201) {
                $this->error($res['data']);
            }
            $res = Program::TextRecognition($params['content'],$user->open_id);
            if($res['code'] == 200 && $res['label'] != 100){
                $this->error($res['data']);
            }elseif ($res['code'] == 201) {
                $this->error($res['data']);
            }
        }
        //敏感词判断
        $sensitive = UserCircleModel::sensitivewords();
        $filteredTitle = replaceSensitiveWords($params['title'], $sensitive);
        $data["title"] = $filteredTitle;
        $post_content = replaceSensitiveWords($params['content'],$sensitive);
        //关键词判断
        $keywords = UserCircleModel::circleKeywords();
        $titleContainsSensitiveWords = containsSensitiveWords($params['title'], $keywords);
        $contentContainsSensitiveWords = containsSensitiveWords($params['content'], $keywords);
        if ($titleContainsSensitiveWords || $contentContainsSensitiveWords) {
            //echo "标题或内容中包含敏感关键词";
            $is_see = 1;
        } else {
            //echo "标题和内容中都不包含敏感关键词";
            $is_see = 0;
        }
        $data["content"] = $post_content;
        $data["user_id"] = $user_id;
        $data['is_see'] = $is_see;
        $data['authen'] = 1;
        if(isset($params["image"])){
            $data["image"] = parse_url($params["image"])["path"];
        }
        if(isset($params["content_images"]) && !empty($params["content_images"])){
            $content_images = explode(",",$params["content_images"]);
            foreach ($content_images as $key=>&$value){
                if($user->open_id){
                    $res = Program::VideoRecognition(parse_url($value)["path"],2,$user->open_id);
                    if($res['code'] == 200 && $res['label'] != 100){
                        $this->error($res['data']);
                    }elseif ($res['code'] == 201) {
                        $this->error($res['data']);
                    }
                }
                $value = parse_url($value)["path"];
            }
            $content_images_str = implode(",",$content_images);
        }else{
            $content_images_str = "";
        }
        $data["content_images"] = $content_images_str;
        if(containsPhoneNumber($post_content)){
            $this->error("帖子内容不能包含手机号");
        }
        if(empty($params['version']) || empty($params['duan'])){
            $this->error("参数异常");
        }
        $info = Db::name("version")->where(["newversion"=>$params["version"],"duan"=>$params["duan"]])->order("id","desc")->find();
        if(!$info){
            $this->error("当前版本信息有误");
        }
        if($info['status'] != '3'){
            UserCircleModel::where("id",$circle_id)->update($data);
            $this->success("修改成功");
        }
        if($params['is_top'] == 0 && $params['cate_top'] == 0 && $user["authen"] == 3 && $edit_price == 0){
            $circle_info = UserCircleModel::get($circle_id);
            $circle_log = [];
            $circle_log['circle_id'] = $circle_id;
            $circle_log['content'] = json_encode($circle_info);
            $circle_log['authen'] = 1;
            $circle_log['addtime'] = time();
            Db::name("user_circle_log")->insert($circle_log);
            UserCircleModel::where("id",$circle_id)->update($data);
            $this->success("修改成功");
        }elseif ($circle_info->istong == 1 && $user["authen"] == 3 && $circle_info->index_top == $params['index_top']){
            $circle_info = UserCircleModel::get($circle_id);
            $circle_log = [];
            $circle_log['circle_id'] = $circle_id;
            $circle_log['content'] = json_encode($circle_info);
            $circle_log['authen'] = 1;
            $circle_log['addtime'] = time();
            Db::name("user_circle_log")->insert($circle_log);
            UserCircleModel::where("id",$circle_id)->update($data);
            $this->success("修改成功");
        }elseif ($circle_info->istong == 1 && $user["authen"] == 3 && $circle_info->cate_top == $params['cate_top']){
            $circle_info = UserCircleModel::get($circle_id);
            $circle_log = [];
            $circle_log['circle_id'] = $circle_id;
            $circle_log['content'] = json_encode($circle_info);
            $circle_log['authen'] = 1;
            $circle_log['addtime'] = time();
            Db::name("user_circle_log")->insert($circle_log);
            UserCircleModel::where("id",$circle_id)->update($data);
            $this->success("修改成功");
        }else{
            if($params['is_top'] != 0){
                $index_top_info = Db::name("topprice")->where(["type"=>1,"day"=>$params['index_top']])->find();
                if(!$index_top_info){
                    $this->error("首页置顶天数错误");
                }
                if($params["index_top_price"] != $index_top_info["price"]){
                    $this->error("首页置顶金额错误");
                }
            }
            if($params["cate_top"] != 0){
                $cate_top_info = Db::name("topprice")->where(["type"=>2,"day"=>$params["cate_top"]])->find();
                if(!$cate_top_info){
                    $this->error("分类置顶天数错误");
                }
                if($params["cate_top_price"] != $cate_top_info["price"]){
                    $this->error("分类置顶金额错误");
                }
            }
            if($circle_info->istong == 1 && $user["authen"] == 3){
                $pay_price = bcadd($params['index_top_price'],$params['cate_top_price'],2);
            }elseif ($circle_info->istong == 1 && $user["authen"] != 3){
                $pay_price = bcadd($edit_price,bcadd($params['index_top_price'],$params['cate_top_price'],2),2);
            }else{
                $pay_price = bcadd($circle_price,bcadd($params['index_top_price'],$params['cate_top_price'],2),2);
            }
            if($params['pay_price'] != $pay_price){
                $this->error("支付金额错误");
            }
            $data["authen"] = 1;
            // UserCircleModel::where("id",$circle_id)->update($data);
            
            $circle_info = UserCircleModel::get($circle_id);
            $circle_log = [];
            $circle_log['circle_id'] = $circle_id;
            $circle_log['content'] = json_encode($circle_info);
            $circle_log['authen'] = 1;
            $circle_log['addtime'] = time();
            Db::name("user_circle_log")->insert($circle_log);
            if($circle_info->user_circle_price_id > 0 && ($circle_info->index_top_endtime > time()) || ($circle_info->cate_top_endtime > time())){
                UserCircleModel::where("id",$circle_id)->update($data);
                $this->success("修改成功");
            }
            UserCircleModel::where("id",$circle_id)->update($data);
            if($pay_price>0)
            {
                $order_no = order_no("F");
                $circle_price_data = [];
                $circle_price_data['user_id'] = $user_id;
                $circle_price_data['circle_id'] = $circle_id;
                $circle_price_data['index_top'] = $params['index_top'];
                $circle_price_data['cate_top'] = $params['cate_top'];
                $circle_price_data['index_top_price'] = $params['index_top_price'];
                $circle_price_data['cate_top_price'] = $params['cate_top_price'];
                $circle_price_data['circle_price'] = $circle_price;
                $circle_price_data['price'] = $params['pay_price'];
                $circle_price_data['order_no'] = $order_no;
                $circle_price_data['ispay'] = 0;
                $circle_price_data['duan'] = $params['duan'];
                UserCirclePriceModel::create($circle_price_data);
                if($params['duan'] == 1){
                    $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','发帖置顶');
                    return json_encode($pay_message);
                }else{
                    $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','发帖置顶');
                    return json_encode($pay_message);
                }
            }
            else
            {
                $this->success("修改成功");
            }

        }
    }

    /**
     * 批量取消收藏
     * @path api/posts/batchCancellation
     */
    public function batchCancellation()
    {
        $circle_str = $this->request->param("circle_str");
        if(!$circle_str){
            $this->error("帖子id不能为空");
        }
        Db::name("collect")->where("circle_id","IN",$circle_str)->delete();
        $this->success('取消成功');
    }

    /*
     * 在售已售
     * @path api/posts/saleCircle
     * */
    public function saleCircle()
    {
        $user_id = $this->auth->user_id;
        $circle_id = $this->request->param("circle_id");
        $is_sale = $this->request->param("issale");
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        if(!$is_sale){
            $this->error("状态不能为空");
        }
        $where = "user_id = {$user_id}";
        $where.= " AND id = {$circle_id}";
        $info = UserCircleModel::where($where)->find();
        $info->issale = $is_sale;
        $info->save();
        $this->success('操作成功');
    }

    /*
     * 置顶帖子
     * @path api/posts/topCircle
     * */
    public function topCircle()
    {
        $params = $this->request->param();
        if($params['index_top'] == "不置顶"){
            $params['index_top'] = 0;
        }
        if($params['cate_top'] == "不置顶"){
            $params['cate_top'] = 0;
        }
        if(!isset($params["duan"])){
            $this->error("缺少参数duan");
        }
        if(!$params["duan"]){
            $this->error("端不能为空");
        }
        $circle_str = $this->request->param("circle_str");
        if(!$circle_str){
            $this->error("帖子id不能为空");
        }
        $circle_arr = UserCircle::where("id","IN",$circle_str)->field("id,authen,index_top,index_top_time,index_top_endtime,cate_top,cate_top_time,cate_top_endtime")->select();
        foreach ($circle_arr as &$value){
//            if($params['index_top'] && $value['index_top_endtime'] > time()){
//                $this->error("存在首页已置顶的帖子");
//            }
//            if($params['cate_top'] && $value['cate_top_endtime'] > time()){
//                $this->error("存在分类已置顶的帖子");
//            }
            if($value['authen'] != '2'){
                $this->error("存在不是审核通过的帖子");
            }
        }
        $circle_price = ConfigModel::getConfigValue("circle_price");
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if($user["authen"] == 3){
            $circle_price = 0;
        }
        $order_no = order_no("ZD");
        $circle_price_data = [];
        $circle_price_data['user_id'] = $user_id;
        $circle_price_data['circle_id'] = $circle_str;
        $circle_price_data['index_top'] = $params['index_top'];
        $circle_price_data['cate_top'] = $params['cate_top'];
        $circle_price_data['index_top_price'] = $params['index_top_price'];
        $circle_price_data['cate_top_price'] = $params['cate_top_price'];
        $circle_price_data['circle_price'] = $circle_price;
        $circle_price_data['price'] = $params['price'];
        $circle_price_data['order_no'] = $order_no;
        $circle_price_data['ispay'] = 0;
        $circle_price_data['duan'] = $params['duan'];
        UserCirclePriceModel::create($circle_price_data);
//        if($user_id == 1 || $user_id == 23){
//            UserCirclePriceModel::topNotify($order_no);
//            $this->success("置顶成功");
//        }else{
            if($params['duan'] == 1){
                $pay_message = (new WxPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','置顶帖子');
                return json_encode($pay_message);
            }else{
                $pay_message = (new AppPay())->wxpay($user_id,$order_no,protocol_name() . '://' . $_SERVER['SERVER_NAME'].'/api/Notify/wxNotify','置顶帖子');
                return json_encode($pay_message);
            }
//        }
    }

    /**
     * 我的收藏
     * @path api/posts/myCollection
     */
    public function myCollection()
    {
        $page = $this->request->param("page",1);
        $is_sale = $this->request->param("issale",0);
        $user_id = $this->auth->user_id;
        $list = UserCircleModel::get_my_collection($page,$user_id,$is_sale);
        $this->success("请求成功",$list);
    }

    /**
     * 设置不看某个人的帖子
     * @path api/posts/noSee
     */
    public function noSee()
    {
        $user_id = $this->auth->user_id;
        $circle_id = $this->request->post("circle_id");
        if(!$circle_id){
            $this->error("帖子id不能为空");
        }
        $info = UserCircleModel::get($circle_id);
        if(!$info){
            $this->error("帖子id错误");
        }
        $other_id = UserCircleModel::where("id",$circle_id)->value("user_id");
        $see_info = Db::name("see")->where(["user_id"=>$user_id,"other_id"=>$other_id])->find();
        if(!$see_info){
            $see_data = [];
            $see_data['user_id'] = $user_id;
            $see_data['other_id'] = $other_id;
            $see_data['create_time'] = time();
            Db::name("see")->insert($see_data);
        }
        $this->success("设置成功");

    }



}
